package com.yjf.service.impl;

import com.yjf.pojo.LagouAuthCode;
import com.yjf.pojo.LagouToken;
import com.yjf.pojo.UserInfo;
import com.yjf.repository.UserInfoRepository;
import com.yjf.response.CommonRespBuilder;
import com.yjf.response.ICommonResponse;
import com.yjf.service.IServiceCodeService;
import com.yjf.service.LagouTokenService;
import com.yjf.service.UserInfoService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Administrator 岳剑飞
 * @date
 * @description:
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private LagouTokenService lagouTokenService;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Reference
    private IServiceCodeService iServiceCodeService;

    @Override
    public ICommonResponse addUserInfo( String code, HttpServletResponse response,String email, String password) throws Exception {

        List<LagouAuthCode> lagouAuthCodes = iServiceCodeService.findAuthCodeByEmail(email);

        LagouAuthCode lagouAuthCode = lagouAuthCodes.get(0);
        Date expiretime = lagouAuthCode.getExpiretime();
        Date now = new Date();

        //验证码过期时
        if (now.compareTo(expiretime) == 1) {
            throw new RuntimeException("验证码超时！");
        }


        if (lagouAuthCodes.size() > 0) {
            if (lagouAuthCodes.get(0).getCode().equals(code)) {
                UserInfo userInfo = new UserInfo();
                userInfo.setEmail(email);
                userInfo.setPassword(password);
                LagouToken lagouToken = new LagouToken();
                lagouToken.setToken(UUID.randomUUID().toString());
                lagouToken.setEmail(email);
                lagouTokenService.saveToken(lagouToken);

                userInfoRepository.save(userInfo);
                Cookie cookie = new Cookie("token",lagouToken.getToken());
                //不设置这个浏览器获取不到cookie
                cookie.setPath("/");
                response.addCookie(cookie);
                return CommonRespBuilder.builder().createSuccessResp().build();
            }
            throw new RuntimeException("验证码错误！");
        }
        return CommonRespBuilder.builder().createFailResp().build();
    }


    @Override
    public UserInfo findUserInfo(String email) {
        return userInfoRepository.findByEmail(email);
    }
}
